<?php
/**
 * Copyright (c) 2011 Bart Visscher <bartv@thisnet.nl>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */
OCP\JSON::checkAppEnabled('calendar');

if( !OC_USER::isLoggedIn() ) {
   jexit(jsonError('您需要先登录', null, false));
}

if (!PSession::checkToken('post')) {
   jexit(jsonError('验证已失效，请重新验证', null, false));
}

$jobid = JRequest::getInt('jobid', 0);
$object_model = new PCalendarModelObject();
$app_model = new PCalendarModelApp();
$post = JRequest::get("post");

if( !PCompanyHelper::checkJobManagerPermissions($jobid) ) {
   jexit(jsonError('您没有管理该职位面试的权限！', null, false));
}

// Check CURD Permissions
if ( !$object_model->checkPermissions($post) ) {
   jexit(jsonError($object_model->getError(), null, false));
}

$reback = $object_model->validateRequest($post);
if (!$reback) {
   jexit(jsonError($object_model->getError(), null, false));
}else{
   $post = $reback;
}

$id = JRequest::getInt('id', 0);
$lastmodified = JRequest::getString('lastmodified', '');

if(!array_key_exists('calendar', $post)) {
   $cal = $object_model->getCalendarid($id);
   $post['calendar'] = $cal;
}else{
   $cal = $post['calendar'];
}

$data = $app_model->getEventObject($id, false, false);
$vcalendar = OC_VObject::parse($data['calendardata']);

if ( !$app_model->isNotModified($vcalendar->VEVENT, $lastmodified) ) {
   jexit(jsonError($app_model->getError(), null, false));
}

$object_model->updateVCalendarFromRequest($post, $vcalendar);

if ( !$object_model->edit($id, $vcalendar->serialize(), $post, $jobseekeremailsent, $intervieweremailsent) ) {
   jexit(jsonError($object_model->getError(), null, false));
}

$jobseeker_stat = 0;
$interviewer_stat = 0;
if($jobseekeremailsent){
   $jobseeker_stat = 1;
}
if($intervieweremailsent){
   $interviewer_stat =1;
}

jexit(jsonSuccess(array('jobseeker_email_stat'=>$jobseeker_stat,'interviewer_email_stat'=>$interviewer_stat,'msg'=>'修改成功'), null, null, false));
